﻿using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;


namespace Magenic.CodeMastery.SharePoint.PMO
{
    [Guid("0ed1c0c4-2f9e-4be9-8ed3-1ea9c4942c40")]
    public class GanttWebPart : WebPart
    {
        private bool error = false;

        //[Personalizable(PersonalizationScope.Shared)]
        //[WebBrowsable(true)]
        //[System.ComponentModel.Category("PMO")]
        //[WebDisplayName("Year")]
        //public int Year { get; set; }
                
        public GanttWebPart()
        {
            this.ExportMode = WebPartExportMode.All;
        }

        /// <summary>
        /// Create all your controls here for rendering.
        /// Try to avoid using the Render() method.
        /// </summary>
        protected override void CreateChildControls()
        {
            if (!error)
            {
                try
                {
                    base.CreateChildControls();

                    GanttControl ctrl = (GanttControl)this.Page.LoadControl("~/_controltemplates/PMO/GanttControl.ascx");
                    ctrl.LoadProjects(2010);
                    
                    this.Controls.Add(ctrl);
                }
                catch (Exception ex)
                {
                    HandleException(ex);
                }
            }
        }

        /// <summary>
        /// Ensures that the CreateChildControls() is called before events.
        /// Use CreateChildControls() to create your controls.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {
            if (!error)
            {
                try
                {
                    base.OnLoad(e);
                    this.EnsureChildControls();
                }
                catch (Exception ex)
                {
                    HandleException(ex);
                }
            }
        }

        /// <summary>
        /// Clear all child controls and add an error message for display.
        /// </summary>
        /// <param name="ex"></param>
        private void HandleException(Exception ex)
        {
            this.error = true;
            this.Controls.Clear();
            this.Controls.Add(new LiteralControl(ex.Message));
        }
    }
}